package com.cus.tom.transfer.frag;

import static com.plata.base.aclr.utils.NetworkUtils.close;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.cus.tom.transfer.ac.ChooseAct;
import com.cus.tom.transfer.adapter.SendInfoAdapter;
import com.cus.tom.transfer.bean.Const;
import com.cus.tom.transfer.databinding.FragInfoBinding;
import com.cus.tom.transfer.utils.Read;
import com.cus.tom.transfer.utils.Utils;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.OnPermissionPageCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class InfoFragment extends BaseFragment {

    SendInfoAdapter adapter;
    FragInfoBinding binding;
    final int type, index;

    public InfoFragment(int type, int index) {
        this.type = type;
        this.index = index;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragInfoBinding.inflate(inflater, container, false);
        adapter = new SendInfoAdapter(binding.linear, this);
        if (type == 1) {
            int p = Utils.dp2Px(getActivity(), 15);
            binding.linear.setPadding(p, 0, p, 0);
            binding.frameAll.setVisibility(View.VISIBLE);
            binding.all.setOnClickListener(v -> {
                boolean bo = !v.isSelected();
                adapter.selectAll(bo);
            });
            loadData();
        }

        return binding.getRoot();
    }

    private void setSize(long size, int index) {
        if (type == 0) {
            ((ChooseAct) getActivity()).setSize(size, index);
        }
    }

    private void loadContractor() {
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                List list = new Read().getContract();
                long size;
                if (!list.isEmpty()) {
                    String str = new Gson().toJson(list);
                    File f = new File(Const.CONTRACT_PATH);
                    FileOutputStream out = null;
                    try {
                        out = new FileOutputStream(f);
                        out.write(str.getBytes());
                        out.flush();
                    } catch (Throwable e) {
                        close(out);
                    }
                    size = f.length();
                } else {
                    size = 0;
                }
                h.post(() -> {
                    adapter.notifyItemChanged(0, list.size(), size);
                    setSize(size, 0);
                });
            }

            @Override
            public long getTimeout() {
                return 0;
            }
        });
    }

    private void loadSms() {
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                List list = new Read().getAllSms();
                long size;
                if (!list.isEmpty()) {
                    String str = new Gson().toJson(list);
                    File f = new File(Const.SMS_PATH);
                    FileOutputStream out = null;
                    try {
                        out = new FileOutputStream(f);
                        out.write(str.getBytes());
                        out.flush();
                    } catch (Throwable e) {
                        close(out);
                    }
                    size = f.length();
                } else {
                    size = 0;
                }
                h.post(() -> {
                    adapter.notifyItemChanged(1, list.size(), size);
                    setSize(size, 1);
                });
            }

            @Override
            public long getTimeout() {
                return 0;
            }
        });
    }

    private void loadPhoneCall() {
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                List list = new Read().getCalls();
                long size;
                if (!list.isEmpty()) {
                    String str = new Gson().toJson(list);
                    File f = new File(Const.CALL_PATH);
                    FileOutputStream out = null;
                    try {
                        out = new FileOutputStream(f);
                        out.write(str.getBytes());
                        out.flush();
                    } catch (Throwable e) {
                        close(out);
                    }
                    size = f.length();
                } else {
                    size = 0;
                }
                h.post(() -> {
                    adapter.notifyItemChanged(2, list.size(), size);
                    setSize(size, 2);
                });
            }

            @Override
            public long getTimeout() {
                return 0;
            }
        });
    }

    private void loadInfo(List<String> permissions) {
        if (permissions.contains(Permission.READ_CONTACTS)) {
            loadContractor();
        }
        if (permissions.contains(Permission.READ_SMS)) {
            loadSms();
        }
        if (permissions.contains(Permission.READ_CALL_LOG)) {
            loadPhoneCall();
        }
    }


    public void askPermission(int i) {
        String p;
        switch (i) {
            case 0:
                p = Permission.READ_CONTACTS;
                break;
            case 1:
                p = Permission.READ_SMS;
                break;
            case 2:
                p = Permission.READ_CALL_LOG;
                break;
            default:
                return;
        }
        XXPermissions.with(this).permission(p)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!permissions.isEmpty()) {
                            loadInfo(permissions);
                        }
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            TipDlg dlg = new TipDlg().setMsg("权限被永久拒绝，请手动授予权限");
                            dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                                @Override
                                public void onDismiss(boolean isOk, Object value) {
                                    if (isOk) {
                                        XXPermissions.startPermissionActivity(
                                                InfoFragment.this, p, new OnPermissionPageCallback() {
                                                    @Override
                                                    public void onGranted() {
                                                        loadInfo(permissions);
                                                    }

                                                    @Override
                                                    public void onDenied() {
                                                    }
                                                });
                                    }
                                }
                            });
                            dlg.show(getChildFragmentManager(), "");
                        }
                    }
                });
    }

    public void loadData() {
        ArrayList<String> list = new ArrayList<>();
        if (XXPermissions.isGranted(getActivity(), Permission.READ_SMS)) {
            list.add(Permission.READ_SMS);
        }
        if (XXPermissions.isGranted(getActivity(), Permission.READ_CONTACTS)) {
            list.add(Permission.READ_CONTACTS);
        }
        if (XXPermissions.isGranted(getActivity(), Permission.READ_CALL_LOG)) {
            list.add(Permission.READ_CALL_LOG);
        }
        if (!list.isEmpty()) {
            loadInfo(list);
        }
    }

    HashSet<Integer> select = new HashSet<>();

    public void updateSelect(int i, boolean bo) {
        if (type == 0) {
            ((ChooseAct) getActivity()).updateSelect(i, bo);
        } else {
            if (bo) {
                select.add(i);
            } else {
                select.remove(i);
            }
            if (select.size() == 3) {
                binding.all.setSelected(true);
            } else {
                binding.all.setSelected(false);
            }
            ((FileFragment) getParentFragment()).updateBtn(select.contains(0) ? 1 : 0, 4);
            ((FileFragment) getParentFragment()).updateBtn(select.contains(1) ? 1 : 0, 5);
            ((FileFragment) getParentFragment()).updateBtn(select.contains(2) ? 1 : 0, 6);
        }
    }
}
